package com.dd.census.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.HandlerInterceptor;

import com.dd.census.tools.TokenHelper;

public class CorsInterceptor implements HandlerInterceptor {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setHeader("Access-Control-Allow-Headers", "Content-Type,X-Token");
		response.setHeader("Access-Control-Allow-Method", "*");

		
		if (request.getRequestURI().indexOf("/user/login") == -1 && request.getRequestURI().indexOf("/userLogin/login") == -1
				&& request.getRequestURI().indexOf("/file/upload") == -1 && request.getRequestURI().indexOf("/file/preview") == -1) {
			if (!request.getMethod().equals("OPTIONS")) {
				String token = request.getHeader("X-Token");
				// 在已登录用户中不存在
				if (!TokenHelper.isVaild(token) ) {
					if (request.getMethod().equals("GET") && (request.getRequestURI().indexOf("/file/download") > -1
							|| request.getRequestURI().indexOf("/file/preview") > -1)) {
						String token2 = request.getParameter("X-Token");
						if (!TokenHelper.isVaild(token2)) {
							response.setStatus(HttpStatus.UNAUTHORIZED.value());
							return false;
						}
					} else {
						response.setStatus(HttpStatus.UNAUTHORIZED.value());
						return false;
					}
				}
			}
		}
		return HandlerInterceptor.super.preHandle(request, response, handler);
	}

}
